package fuck.loader;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import fuck.ActionContext;
import fuck.config.ExcelConfig;

public class ConfigXMLLoader {
	public ExcelConfig load(ActionContext context, IFile file) {
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			InputStream is = file.getContents();
			Document document = builder.parse(is);
			Node root = document.getElementsByTagName("configs").item(0);

			ExcelConfig config = new ExcelConfig();

			Node node = root.getFirstChild();
			while (node != null) {
				if ("db-config".equals(node.getNodeName()))
					config.setDbConfig(node.getTextContent());
				else if ("java-project".equals(node.getNodeName()))
					config.setJavaProject(node.getTextContent());
				else if ("java-excel-package".equals(node.getNodeName()))
					config.setJavaExcelPackage(node.getTextContent());
				else if ("java-excel-pool".equals(node.getNodeName()))
					config.setJavaExcelPool(node.getTextContent());
				else if ("as-recourse".equals(node.getNodeName()))
					config.setAsRecourse(node.getTextContent());
				else if ("as-project".equals(node.getNodeName()))
					config.setAsProject(node.getTextContent());
				else if ("as-excel-package".equals(node.getNodeName())) {
					config.setAsExcelPackage(node.getTextContent());
				}
				node = node.getNextSibling();
			}
			is.close();

			return config;
		} catch (CoreException e) {
			context.getMcs().println(e.getMessage());
		} catch (ParserConfigurationException e) {
			context.getMcs().println(e.getMessage());
		} catch (IOException e) {
			context.getMcs().println(e.getMessage());
		} catch (SAXException e) {
			context.getMcs().println(e.getMessage());
		} catch (Exception e) {
			context.getMcs().println(e.getMessage());
		}

		return null;
	}
}
